<script lang="ts">
  import BroadcastComp from './components/Broadcast.svelte';
  import { getIsShow } from './api/index';
  import BroadcastMini from './components/BroadcastMini.svelte';
  import { BroadcastStatus, type Position } from './types/vtuber';
  import {
    errorReport,
    sendStat,
    judgeChrome49,
    getFile,
    toggleAutoPlay,
    getClientId,
    getUserId
  } from './utils/tools';
  import { AvatarType } from './types/broadcastMini';
  import config from '../lib/config/index';
  export let miniDragable: boolean = true;
  export let position: {
    min: Position;
    max: Position;
  };
  export let avatarType: AvatarType = AvatarType.Gold;
  // 当前组件是否展示
  let isShow: boolean = false;
  let isMini: boolean = true;
  let broadcastDom;

  // 防止延时关闭期间重新打开，设置定时器
  let showMaxTimer;
  // 切换最小化和最大化状态
  const toggleMiniStatus = ({ detail: { isMiniStatus, isClose } }) => {
    isMini = isMiniStatus;
    if (!isMini) {
      showMaxTimer && clearTimeout(showMaxTimer);
      showMax = true;
      broadcastDom && broadcastDom.setMaxPlay();
      sendStat('_cpsy_zxhrk_dj');
    }
    if (isClose) {
      // 动画200ms,稍微晚点再断开长连接和退出引擎
      showMaxTimer = setTimeout(() => {
        showMax = false;
      }, 500);
    }
  };

  // 是否是首次进入
  let isFirstEnter: boolean = true;
  // 是否是自动播放
  let isAutoplay: boolean = false;
  // 当前是否正在播放
  let isPlaying: boolean = false;

  // 开始播报的时间
  let startTime: Date | void;

  // 是否是chrome49
  const isChrome49: boolean = judgeChrome49();

  const updateBroadcastStatus = ({ detail: { broadcastStatus } }) => {
    const options = {
      [BroadcastStatus.IsFirstEnter]: () => {
        isFirstEnter = true;
        isAutoplay = false;
      },
      [BroadcastStatus.Autoplay]: () => {
        isFirstEnter = false;
        isAutoplay = true;
      }
    };
    if (options[broadcastStatus]) {
      options[broadcastStatus]();
    } else {
      isFirstEnter = false;
      isAutoplay = false;
    }
  };

  const updateIsPlaying = ({ detail: { isPlayingStatus } }) => {
    isPlaying = isPlayingStatus;
    if (isPlaying) {
      startTime = new Date();
    } else {
      if (!startTime) {
        return;
      }
      const nowTime = new Date();
      const diffTime = nowTime.getTime() - startTime.getTime();
      sendStat(`_zxh_bfzt_${diffTime / 1000}`);
    }
  };

  //  切换自动播放
  const toggleAutoplay = () => {
    toggleAutoPlay(nowuerid);
    isAutoplay = !isAutoplay;
    const stat = isAutoplay ? '_dhym_kqzdbb_2' : '_dhym_gbzdbb_2';
    sendStat(stat);
  };

  // 是否展示最大化
  let showMax: boolean = false;
  let nowuerid: string = '';
  // 实例化前判断是否自动播放
  const getIsAutoPlay = () => {
    getUserId().then((userid: string) => {
      nowuerid = userid;
      const {
        localstorageKeys: { firstEnterKey, autoPlayKey }
      } = config;

      const firstEnterKeyUserid = `${firstEnterKey}${userid}`;
      const autoPlayKeyUserid = `${autoPlayKey}${userid}`;
      getFile(firstEnterKeyUserid).then((status) => {
        if (status) {
          getFile(autoPlayKeyUserid).then((autoplayStatus: boolean) => {
            // 是否是自动播放
            isAutoplay = !!autoplayStatus;
            showMax = isAutoplay;
          });
          isFirstEnter = false;
        } else {
          isFirstEnter = true;
        }
      });
    });
  };

  getIsAutoPlay();

  getIsShow()
    .then((res) => {
      if (res?.data) {
        const { is_show, client_ids, user_id_tail } = res?.data;
        if (!is_show) {
          return;
        }
        Promise.all([getClientId(), getUserId()]).then(([clientId, userId]) => {
          const useridTail = (userId + '').slice(-1);
          if (
            // @ts-ignore
            (client_ids.includes(clientId + '') || !client_ids.length) &&
            (user_id_tail.includes(+useridTail) || !user_id_tail.length)
          ) {
            isShow = true;
          }
        });
      }
    })
    .catch((error: Error) => {
      errorReport({
        name: `获取组件是否展示报错 ${error.name}`,
        message: error.message,
        stack: error.stack
      });
    });

  export const getIsMini = (): boolean => isMini;
  export const endBroadcast = () => {
    broadcastDom && broadcastDom.endBroadcast(false);
  };
</script>

<div class="vtuber-comp">
  {#if isShow}
    {#if isChrome49}
      <BroadcastMini position={position.min} dragAble={miniDragable} {isChrome49} />
    {:else}
      <BroadcastMini
        isShow={isMini}
        position={position.min}
        {avatarType}
        {isPlaying}
        {isAutoplay}
        {isFirstEnter}
        dragAble={miniDragable}
        on:toggleMiniStatus={toggleMiniStatus}
        on:toggleAutoplay={toggleAutoplay}
        on:turnoffPlay={endBroadcast}
      />
      {#if showMax}
        <BroadcastComp
          bind:this={broadcastDom}
          isShow={!isMini}
          position={position.max}
          on:updateBroadcastStatus={updateBroadcastStatus}
          on:updateIsPlaying={updateIsPlaying}
          on:toggleMiniStatus={toggleMiniStatus}
        />
      {/if}
    {/if}
  {/if}
</div>

<style lang="less">
  .vtuber-comp {
    margin: initial;
    :global(div),
    :global(span),
    :global(h1),
    :global(p),
    :global(a),
    :global(ol),
    :global(input) {
      margin: initial;
    }
  }
</style>
